from scheduler import app
import importlib
from scheduler.model import CeleryBeatTaskInfo, CeleryBeatTaskLog
from scheduler.serializer import TaskInfoSerializer
import celery
from celery import current_task
import json
import traceback
# from celery.task import task
#
#
# class MyTask(celery.Task):
#     # 任务失败时执行
#     def on_failure(self, exc, task_id, args, kwargs, einfo):
#         print('{0!r} failed: {1!r}'.format(task_id, exc))
#         TaskLog.update(task_id, False, einfo)
#     # 任务成功时执行
#     def on_success(self, retval, task_id, args, kwargs):
#         TaskLog.update(task_id, True)
#     # 任务重试时执行
#     def on_retry(self, exc, task_id, args, kwargs, einfo):
#         pass


@app.task
def crontab_task(*args, **kwargs):
    entry_name = kwargs.pop('__entry_name')
    module_path = entry_name
    module_object = importlib.import_module(module_path)

    try:
        celery_beat_task_info = TaskInfoSerializer().dump(CeleryBeatTaskInfo.session.query(CeleryBeatTaskInfo).filter_by(name=entry_name).first())
        kwargs.update({'task_info': celery_beat_task_info})
        result, message = module_object.main(*args, **kwargs)
        CeleryBeatTaskLog.add(task_id=current_task.request.id, task=current_task.request.task, name=entry_name,
                    args=json.dumps(args), kwargs=json.dumps(kwargs), result=result, message=message)
        return result
    except Exception as e:
        CeleryBeatTaskLog.add(task_id=current_task.request.id, task=current_task.request.task, name=entry_name,
                    args=json.dumps(args),  kwargs=json.dumps(kwargs), result=False, message=traceback.format_exc())
        raise e


if __name__ == '__main__':
    crontab_task(**{'__entry_name': 'source.city_beijing'})

